package me.work.pay.jsyl.mvp.ui.activity;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.allenliu.versionchecklib.callback.DownloadListener;
import com.allenliu.versionchecklib.utils.FileHelper;
import com.allenliu.versionchecklib.v2.net.DownloadMangerV2;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chaomeng.a8sdklibrary.event.WifiInfoEvent;
import com.chaomeng.a8sdklibrary.keyparser.KeyBoardUtils;
import com.chaomeng.a8sdklibrary.utils.LogUtil;
import com.danikula.videocache.HttpProxyCacheServer;
import com.google.gson.Gson;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;
import com.yzy.voice.ReturnPayResult;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.work.pay.jsyl.R;
import me.work.pay.jsyl.app.Constants;
import me.work.pay.jsyl.app.RouterHub;
import me.work.pay.jsyl.app.mqtt.IGetMessageCallBack;
import me.work.pay.jsyl.app.mqtt.MyServiceConnection;
import me.work.pay.jsyl.app.service.MQTTService;
import me.work.pay.jsyl.app.utils.NumberPlayer;
import me.work.pay.jsyl.app.utils.QRCodeUtil;
import me.work.pay.jsyl.app.utils.RxUtil;
import me.work.pay.jsyl.app.utils.SoundMaker;
import me.work.pay.jsyl.app.utils.Utils;
import me.work.pay.jsyl.app.utils.WifiToolUtil;
import me.work.pay.jsyl.di.component.DaggerGroupListComponent;
import me.work.pay.jsyl.mvp.contract.GroupListContract;
import me.work.pay.jsyl.mvp.model.AppModel;
import me.work.pay.jsyl.mvp.model.entity.GuanGaoData;
import me.work.pay.jsyl.mvp.model.entity.LauncherData;
import me.work.pay.jsyl.mvp.model.entity.UpdateInfo;
import me.work.pay.jsyl.mvp.presenter.GroupListPresenter;
import timber.log.Timber;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description: 团队管理
 * <p>
 * Created by MVPArmsTemplate on 10/28/2019 13:20
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@Route(path = RouterHub.APP_GroupListActivity)
public class GroupListActivity extends BaseActivity<GroupListPresenter> implements GroupListContract.View, IGetMessageCallBack {
    public static GroupListActivity activity;
    @BindView(R.id.video)
    VideoView videoView;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.iv)
    ImageView iv;
    @Nullable
    @BindView(R.id.iv2)
    ImageView iv2;
    @Nullable
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.shop_name_tv)
    TextView shop_name_tv;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @Nullable
    @BindView(R.id.rl2)
    RelativeLayout rl2;
    @BindView(R.id.error_iv)
    ImageView error_iv;
    private static final int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;
    private QMUITipDialog mQMUITipDialog;
    private Process process;
    private PrintWriter PrintWriter;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerGroupListComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        if (isLandscape()) {
            if (AppModel.getInstance().getLauncherData().isReverseLand()) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            }else{
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
            return R.layout.activity_main_land;
        } else {
            ScreenUtils.setPortrait(this);
            return R.layout.activity_group_list; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
        }
    }

    private boolean isLandscape() {
        return AppModel.getInstance().getLauncherData().isLandscape();
    }

    String urls[] = {};
    int now_index = 0;
    List<String> images = new ArrayList<>();
    private MyServiceConnection serviceConnection;

    @BindView(R.id.load_view)
    View load_view;

    private void init_mqtt() {
        serviceConnection = new MyServiceConnection();
        serviceConnection.setIGetMessageCallBack(GroupListActivity.this);
        Intent intent = new Intent(this, MQTTService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    public SoundMaker soundMaker;

    private void init_page() {
        SPUtils.getInstance().put(Constants.sp_page_value, "1");
    }

    ConnectivityManager connectivityManager;

    Handler mHandler = new Handler();

    @Subscribe
    public void onEvent(ReturnPayResult result) {
        if (result.result) {
            mPresenter.getGroup();
        } else {
            int type = result.type;
            if (type < 3) {
                MQTTService.publish(result.msg);
            } else {//type=3是用来传日志的
                mPresenter.upload_log(result.msg);
            }
        }
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        activity = this;
        EventBus.getDefault().register(this);
        soundMaker = new SoundMaker(this);

        init_page();
        init_mqtt();
        ScreenUtils.setFullScreen(this);
        KeyBoardUtils.getDefault().init((key, num) -> {

            String page_index = SPUtils.getInstance().getString(Constants.sp_page_value);
            Timber.tag(TAG).e("key:" + key + "--num:" + num + "--page_index:" + page_index);
            Intent intent;
            /**
             * F1-F4
             * prefix：A keyboard：空
             * prefix：B keyboard：空
             * prefix：C keyboard：空
             * prefix：D keyboard：空
             * 0 空
             * . 空
             * 返回 <
             * 清除 X
             * 收款 @ 0
             * */
            switch (key) {
                case "A"://F1
//                    soundMaker.makeSound("1", "0.01");
//                    String s = "10000.01";
//                    MQTTService.publish("msg");
//                    VoicePlay.with(getApplicationContext()).play("111,"+s, true);

//                    intent = new Intent(GroupListActivity.this, PayResultActivity.class);
//                    startActivity(intent);
                    break;
                case "B"://F2
                    if (!check_intent()) {
                        ToastUtils.showShort("请先连接网络");
                        return;
                    }
                    if (now_groupData == null || now_groupData.result_code.equals("fail")) {
                        ToastUtils.showShort("请先绑定设备");
                        return;
                    }
                    if (AppModel.getInstance().getLauncherData().isLandscape()) {
                        if (AppModel.getInstance().getLauncherData().isReverseLand()) {
                            intent = new Intent(GroupListActivity.this, OrderListLandActivity.class);
                        }else{
                            intent = new Intent(GroupListActivity.this, OrderListLand2Activity.class);
                        }
                    } else {
                        intent = new Intent(GroupListActivity.this, OrderListActivity.class);
                    }
                    startActivity(intent);
                    break;
                case "C"://F3
                    ToastUtils.showShort("正在检查更新");
                    mPresenter.check_version();
                    break;
                case "D"://F4
                    open_debug();
                    ToastUtils.showShort(AppUtils.getAppVersionName());
                    break;
                case "<"://返回
                    switch (page_index) {
                        case "1":

                            break;
                        case "2"://支付页面
                            if (PayActivity.main != null) {
                                PayActivity.main.killMyself();
                            }
                            if (PayLandActivity.main != null) {
                                PayLandActivity.main.killMyself();
                            }
                            if (PayLand2Activity.main != null) {
                                PayLand2Activity.main.killMyself();
                            }
                            break;
                        case "4":
                            if (OrderListActivity.main != null) {
                                OrderListActivity.main.killMyself();
                            }
                            if (OrderListLandActivity.main != null) {
                                OrderListLandActivity.main.killMyself();
                            }
                            if (OrderListLand2Activity.main != null) {
                                OrderListLand2Activity.main.killMyself();
                            }
                            break;
                        case "5":
                            if (WifiActivity.main != null) {
                                WifiActivity.main.killMyself();
                            }
                            if (WifiLandActivity.main != null) {
                                WifiLandActivity.main.killMyself();
                            }
                            if (WifiLand2Activity.main != null) {
                                WifiLand2Activity.main.killMyself();
                            }
                            break;
                        default:
                            intent = new Intent(GroupListActivity.this, GroupListActivity.class);
                            startActivity(intent);
                            break;
                    }
                    break;
                case "@"://收款
                    if (!check_intent()) {
                        ToastUtils.showShort("请先连接网络");
                        return;
                    }
                    String qian = num;//当前键盘写的钱，执行收款操作
                    if (TextUtils.isEmpty(qian)) {
                        ToastUtils.showShort("请输入正确的金额");
                    } else {
                        soundMaker.makeSound("3", key);
                    }
                    if (page_index.equals("2")) {
                        EventBus.getDefault().post(new ReturnPayResult(qian));
                    } else {
                        if (isLandscape()) {
                            if (AppModel.getInstance().getLauncherData().isReverseLand()) {
                                intent = new Intent(GroupListActivity.this, PayLandActivity.class);
                            }else {
                                intent = new Intent(GroupListActivity.this, PayLand2Activity.class);
                            }


                        } else {
                            intent = new Intent(GroupListActivity.this, PayActivity.class);
                        }
                        intent.putExtra("money", qian);
                        startActivity(intent);
                    }
                    break;
                case "X"://清除----不需要操作
                    break;
                default://日常摁键
//                    mSoundPool.play(mCSoundId, 1.0f, 1.0f, 0, 0, 1.0f);

//                    new PlaySound().play(this, key);
                    if (key.equals(".")) {
                        NumberPlayer.getInstance().play(10);
                    } else {
                        NumberPlayer.getInstance().play(Integer.parseInt(key));
                    }
//                    soundMaker.StartMusic(Integer.parseInt(key)+1);
//                    soundMaker.makeSound("3",Integer.parseInt(key)+1+"");
                    break;
            }
            Log.e("sea", "prefix = " + key + "  keyboard = " + num);
        });
        String serialNumber = Constants.sn;
        Log.e("serialNumber", serialNumber + "");

        mPresenter.getGroup();
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //获取系统的Audio管理者
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //最大音量
        maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        //当前音量
        currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        connectivityManager = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
        load_data();
        videoView.setOnCompletionListener(mp -> {
            Log.i("aaaapath", urls.length + "");
            if (now_index < urls.length - 1) {
                now_index++;
            } else {
                now_index = 0;
            }
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            Log.i("aaaapath", (info == null) + "");
            if (info == null || now_index == 0) {
                initVideo("");
            } else {
                initVideo(urls[now_index]);
            }
            play_num++;
        });


        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String version = AppUtils.getAppVersionName();
                EventBus.getDefault().post(new ReturnPayResult(2, "{\"sn\":" + Constants.sn +
                        ",\"firmware_version\":\"" + version + "\",\"play_num\":" + play_num + "}"));
                mHandler.postDelayed(this, 5 * 60 * 1000);
                play_num = 0;
            }
        };
        //主线程中调用：
        mHandler.postDelayed(runnable, 5 * 60 * 1000);//延时100毫秒
    }

    private int play_num = 0;//广告播放的次数

    /**
     * 使用AudioManager控制音量
     *
     * @param value
     */
    private void setVoiceVolume(float value) {
        try {
            AudioManager audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//(最大值是15)
            int flag = value > 0 ? -1 : 1;
            currentVolume += flag * 0.1 * maxVolume;
            // 对currentVolume进行限制
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 校验是否联网
     *
     * @return true:联网
     */
    private boolean check_intent() {
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        Log.e("ArmsHttpLog", new Gson().toJson(info));
        return info != null;
    }

    private void open_debug() {
        //  (1 :打开adb调试，2：关闭adb调试工具)
        boolean enableAdb = (Settings.Secure.getInt(getContentResolver(), Settings.Secure.ADB_ENABLED, 0) > 0);
        if (!enableAdb) {
            Settings.Secure.putInt(getContentResolver(), Settings.Secure.ADB_ENABLED, 1);
        }
    }

    /**
     * 加载缓存数据
     */
    private void load_data() {
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        //加载缓存视频
        if (info == null) {
            initVideo("");
            error_iv.setVisibility(View.VISIBLE);
            load_view.setVisibility(View.GONE);
            pay_cach();
        } else {
            error_iv.setVisibility(View.GONE);
        }
    }

    /**
     * 支付的缓存图片
     */
    private void pay_cach() {
        String url = SPUtils.getInstance().getString(Constants.sp_pay_url);
        if (TextUtils.isEmpty(url)) {
            url = Constants.sn;
        }
        Bitmap bitmap = QRCodeUtil.createQRCodeBitmap(url, 200, 200);
        iv.setImageBitmap(bitmap);
        if (isLandscape() && ScreenUtils.isLandscape()) {
            iv2.setImageBitmap(bitmap);
        }
    }

    private void initVideo(String url) {
        HttpProxyCacheServer proxy = RxUtil.getProxy(getApplicationContext());
        //1.我们会将原始url注册进去
        // proxy.registerCacheListener(, bean.getVideo_url());
        //2.我们播放视频的时候会调用以下代码生成proxyUrl
        String proxyUrl = proxy.getProxyUrl(url);
        if (proxy.isCached(url)) {
            Log.i("aaaa", "已缓存");
        } else {
            Log.i("aaaa", "未缓存");
        }
        Log.i("aaaapath1", proxyUrl);
        if (proxyUrl.contains("127.0.0.1")) {
            proxyUrl = "android.resource://me.work.pay.jsyl/" + R.raw.video;
            videoView.setVideoURI(Uri.parse(proxyUrl));
        } else {
            videoView.setVideoPath(proxyUrl);
        }
        videoView.start();
        videoView.findFocus();
    }


    @Override

    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);

        int mCurrentOrientation = getResources().getConfiguration().orientation;

        if (mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            setContentView(R.layout.activity_group_list);

        } else if (mCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            setContentView(R.layout.activity_main_land);
        }
        ButterKnife.bind(this);
        videoView.setOnCompletionListener(mp -> {
            Log.i("aaaapath", urls.length + "");
            if (now_index < urls.length - 1) {
                now_index++;
            } else {
                now_index = 0;
            }
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            Log.i("aaaapath", (info == null) + "");
            if (info == null || now_index == 0) {
                initVideo("");
            } else {
                initVideo(urls[now_index]);
            }
            play_num++;
        });


        update(AppModel.getInstance().getLauncherData());

    }

    private AudioManager mAudioManager;
    private int maxVolume, currentVolume;

    private void sound_change(boolean is_add) {
        if (is_add) {
            if (currentVolume < maxVolume) {
                currentVolume++;
            } else {
                ToastUtils.showShort("当前已是最大音量");
                return;
            }
        } else {
            if (currentVolume > 1) {
                currentVolume--;
            } else {
                ToastUtils.showShort("已是最小音量");
                return;
            }
        }
        Log.e("ArmsHttpLogcurrentVolum", currentVolume + "");
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
        currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        LogUtil.i(TAG, "onKeyDown : " + keyCode);
        switch (keyCode) {
            case 141:
                soundMaker.makeSound("3", "22");//进入配网模式
                Class<?> cls = WifiActivity.class;
                if (AppModel.getInstance().getLauncherData().isLandscape()) {
                    if (AppModel.getInstance().getLauncherData().isReverseLand()) {
                        cls = WifiLandActivity.class;
                    }else{
                        cls = WifiLand2Activity.class;
                    }
                }
                Intent intent = new Intent(GroupListActivity.this, cls);
                startActivity(intent);
                break;
            case 25://音量减
                sound_change(false);
                break;
            case 24://音量加
                sound_change(true);
                break;
        }

        return true;
    }

    LauncherData now_groupData;

    @Override
    public void update(LauncherData groupData) {
        EventBus.getDefault().post(new ReturnPayResult(3, "已联网，" + new Gson().toJson(groupData)));
        now_groupData = groupData;
        if (groupData == null || groupData.result_code == null) {
            load_data();
            return;
        }
        error_iv.setVisibility(View.GONE);
        String url = Constants.sn;
        if (groupData.result_code.equals("success")) {
            url = groupData.aerf_sn.getShort_key_url();
            SPUtils.getInstance().put(Constants.sp_pay_url, url);
            if (isLandscape() && ScreenUtils.isLandscape()) {

                rl.setVisibility(View.GONE);
                rl2.setVisibility(View.VISIBLE);
            } else {
                rl.setBackgroundResource(R.drawable.pay2);
                ll2.setVisibility(View.VISIBLE);
            }
            SPUtils.getInstance().put(Constants.APIKEY, groupData.aerf_sn.getApi_key());
        } else {
            if (isLandscape() && ScreenUtils.isLandscape()) {
                rl.setVisibility(View.VISIBLE);
                rl2.setVisibility(View.GONE);
            } else {
                rl.setBackgroundResource(R.drawable.pay1);
                ll2.setVisibility(View.GONE);
            }

        }
        int autoHeight = RxUtil.getAutoHeight(getApplicationContext(), 160);
        Bitmap bitmap = QRCodeUtil.createQRCodeBitmap(url, autoHeight, autoHeight);

        if (iv2 != null) {
            iv2.setImageBitmap(bitmap);
        }
        iv.setImageBitmap(bitmap);
        images = new ArrayList<>();
        List<GuanGaoData> list = groupData.aerf_adver_down;
        for (GuanGaoData model : list) {
            images.add(model.getUrl());
        }
        error_iv.setVisibility(images.size() == 0 ? View.VISIBLE : View.GONE);
        init_imgs();
        list = groupData.aerf_adver_up;
        urls = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            urls[i] = list.get(i).getUrl();
        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(this,
//                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                        MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
//            } else {
//                Log.i("aaa", "权限已申请");
        if (urls.length > 0) {
            initVideo(urls[0]);
        } else {
            initVideo("");
        }
//            }
//        }
        if (ObjectUtils.isNotEmpty(groupData.aerf_sn)) {
            String shop_name = groupData.aerf_sn.getShort_key_name();
            shop_name_tv.setText(ObjectUtils.isEmpty(shop_name) ? "" : shop_name);
            if (Constants.is_test) {
                SPUtils.getInstance().put(Constants.sp_shop_id, "7898ffe6550cc695ce6d31c248ced1a6");
            } else {
                SPUtils.getInstance().put(Constants.sp_shop_name, shop_name);//店铺名称
                SPUtils.getInstance().put(Constants.sp_shop_id, groupData.aerf_sn.getShop_id());//店铺ID
            }
        }
        load_view.setVisibility(View.GONE);
    }

    @Override
    public void check_version(UpdateInfo info) {
        String version = AppUtils.getAppVersionName();
        if (info.getUpdate().equals("yes")) {
            startDownloadApk(info.getDownloadurl(), info.getVersion());
        } else {
            ToastUtils.showShort("当前是最新版本");
        }

    }

    @Override
    public void requestScreenOrientation() {
        if (ScreenUtils.isPortrait() && AppModel.getInstance().getLauncherData().isLandscape()) {
            if (AppModel.getInstance().getLauncherData().isReverseLand()) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            }else{
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        } else if (ScreenUtils.isLandscape() && !AppModel.getInstance().getLauncherData().isLandscape()) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    public static final int PER_USER_RANGE = 100000;

    public static int getUserId(int uid) {
        return uid / PER_USER_RANGE;
    }

    // 适配android9.0之前的安装方法
    private void startUpdate(String filePath) {

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            // 7.0以后版本需要额外添加
            //           "-i", "当前应用包名",
            // 两个字段，并且需要应用支持 android.permission.INSTALL_PACKAGES 权限**
            process = new ProcessBuilder("pm", "install", "-i", getPackageName(), "-r", filePath).start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception " + e.toString());
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {

            }
            if (process != null) {
                process.destroy();
            }
        }
        Log.e(TAG, "errorMsg " + errorMsg.toString());
        Log.d(TAG, "successMsg " + successMsg.toString());

    }

    private String installApk(String apkPath) {
        QMUITipDialog dialog = RxUtil.showLoading(getActivity(), "正在安装...");
        dialog.show();
        if (TextUtils.isEmpty(apkPath)) {
            return null;
        }
        //pm install -i 包名 –-user 0 apkpath   7.0 版本
        ProcessBuilder processBuilder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String[] args = {"pm", "install", "-i", "me.work.pay.jsyl", "--user", "0", apkPath};
//            String[] args = {"pm", "install", "-r", apkPath};
            processBuilder = new ProcessBuilder(args);
        } else {
            String[] args = {"pm", "install", "-r", apkPath};
            processBuilder = new ProcessBuilder(args);
        }
        String result = "";
        Process process = null;
        InputStream errIs = null;
        InputStream inIs = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read = -1;
            process = processBuilder.start();
            errIs = process.getErrorStream();
            while ((read = errIs.read()) != -1) {
                baos.write(read);
            }
            baos.write('\n');
            inIs = process.getInputStream();
            while ((read = inIs.read()) != -1) {
                baos.write(read);
            }
            byte[] data = baos.toByteArray();
            LogUtil.i(TAG, "data : " + data);
            result = new String(data);
//                ToolsUtil.exeCmd("sync");
//                Thread.sleep(2000);
//                ToolsUtil.exeCmd("sync");
//                Thread.sleep(2000);
//                ToolsUtil.sync();
            LogUtil.i(TAG, "sunc end");
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e(TAG, "install fail " + e);
        } finally {
            try {
                if (errIs != null) {
                    errIs.close();
                }
                if (inIs != null) {
                    inIs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    private void startDownloadApk(String url, String version) {
        //判断是否缓存并且是否强制重新下载
        final String downloadPath = FileHelper.getDownloadApkCachePath();
        File file = new File(downloadPath, "A8_" + version + ".apk");
        if (file.exists()) {
            installApk(file.getPath());
            return;
        }

        DownloadMangerV2.download(url, downloadPath, file.getName(), new DownloadListener() {
            @Override
            public void onCheckerDownloading(int progress) {

            }

            @Override
            public void onCheckerDownloadSuccess(File file) {
                if (mQMUITipDialog == null) {
                    mQMUITipDialog.dismiss();
                    ToastUtils.showShort("下载完成");
                }
                installApk(file.getPath());
            }

            @Override
            public void onCheckerDownloadFail() {
                if (mQMUITipDialog == null) {
                    mQMUITipDialog.dismiss();
                    ToastUtils.showShort("下载失败");
                }
            }

            @Override
            public void onCheckerStartDownload() {
                if (mQMUITipDialog == null) {
                    mQMUITipDialog = RxUtil.showLoading(getActivity(), "正在下载...");
                }
                mQMUITipDialog.show();
            }
        });
    }


    private void init_imgs() {
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL);    //缓存所有版本
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                imageView.setScaleType(ImageView.ScaleType.CENTER);
                Glide.with(context).load(path).apply(options).into(imageView);
            }
        });
        banner.setImages(images);
        banner.start();
        banner.setDelayTime(1500);//设置轮播时间
    }

    private String mSsid = null;
    private String mPswd = null;
    private String mBssid = null;

    @Override
    public void setMessage(String message) {

    }

    @Override
    protected void onDestroy() {
        unbindService(serviceConnection);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWifiInfoEvent(WifiInfoEvent event) {
        if (event != null) {
            if (event.ssid != null) {
                mSsid = event.ssid;
                mPswd = event.pswd;
                mBssid = event.bssid;
                LogUtil.i("CM1", "WifiInfoEvent1 : " + mPswd + "    " + mSsid + "    " + mBssid);
                WifiToolUtil.doConnectWifi(event.bssid, event.ssid, event.pswd, this);
//                wifiManager.disableNetwork(wifiManager.getConnectionInfo().getNetworkId());
//                int netId = wifiManager.addNetwork(getWifiConfig(mSsid, mPswd));
//                wifiManager.enableNetwork(netId, true);
            }
        }
    }

    // 使用 WifiConfiguration 连接.
    public static void connectByConfig(WifiManager manager, WifiConfiguration config) {
        if (manager == null) {
            return;
        }
        try {
            Method connect = manager.getClass().getDeclaredMethod("connect", WifiConfiguration.class, Class.forName("android.net.wifi.WifiManager$ActionListener"));
            if (connect != null) {
                connect.setAccessible(true);
                connect.invoke(manager, config, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    WifiManager wifiManager;

    /**
     * wifi设置
     *
     * @param ssid
     * @param pws
     */
    private WifiConfiguration getWifiConfig(String ssid, String pws) {
        LogUtil.i("ArmsHttpLog", ssid + "到这里了吗？？？wifi密码：" + pws);

        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";

        WifiConfiguration tempConfig = isExist(ssid);
        if (tempConfig != null) {
            wifiManager.removeNetwork(tempConfig.networkId);
        }
        LogUtil.i("ArmsHttpLog", ssid + "wifi密码：" + pws);
        if (!TextUtils.isEmpty(pws)) {
            LogUtil.i("ArmsHttpLog", "wifi密码：" + pws);
//            return setWifiParamsPassword(ssid, pws);
            config.preSharedKey = "\"" + pws + "\"";
            config.hiddenSSID = true;

            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        } else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        return config;
    }


    /**
     * 得到配置好的网络连接
     *
     * @param ssid
     * @return
     */
    private WifiConfiguration isExist(String ssid) {
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration config : configs) {
            if (config.SSID.equals("\"" + ssid + "\"")) {
                Log.e("ArmsHttpLog:", "配网结果：" + new Gson().toJson(config));
                return config;
            }
        }
        return null;
    }


    @Override
    protected void onResume() {
        super.onResume();


        String page = SPUtils.getInstance().getString(Constants.sp_page_value);
        int time = 0;
        if (("5").equals(page)) {
            time = 2000;
        }
        Handler handler = new Handler();
        handler.postDelayed(() -> {
            init_page();
            mPresenter.getGroup();
        }, time);//3秒后执行Runnable中的run方法
        if (videoView != null) {
            videoView.resume();
        }
    }

    @Override
    protected void onPause() {
        if (ScreenUtils.isPortrait() && AppModel.getInstance().getLauncherData().isLandscape()) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
        }
        super.onPause();
        if (videoView != null) {
            videoView.pause();
        }
//        BLEManager.getDefault().unregisterReceiver();
    }

    @Override
    public void showLoading() {
    }

    @Override
    public void hideLoading() {
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public Activity getActivity() {
        return this;
    }


    /*
     * m命令可以通过adb在shell中执行，同样，我们可以通过代码来执行
     */
    public static String execCommand(String... command) {
        Process process = null;
        InputStream errIs = null;
        InputStream inIs = null;
        String result = "";

        try {
            process = new ProcessBuilder().command(command).start();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read = -1;
            errIs = process.getErrorStream();
            while ((read = errIs.read()) != -1) {
                baos.write(read);
            }

            inIs = process.getInputStream();
            while ((read = inIs.read()) != -1) {
                baos.write(read);
            }
            result = new String(baos.toByteArray());

            if (inIs != null)
                inIs.close();
            if (errIs != null)
                errIs.close();
            process.destroy();
        } catch (IOException e) {
            e.printStackTrace();
            result = e.getMessage();
        }

        return result;
    }

    @OnClick(R.id.video)
    public void onClick() {

//        VoicePlay.with(getApplicationContext()).playCancel("7.07");
//        launchActivity(new Intent(this,PayResultLandActivity.class));
    }
}
